<?php

namespace App\Third\Service\Lsy;


use App\Common\Service\BaseService;

class LsyMainGoodsService extends BaseService
{
    /**
     * 用户全量获取商品信息接口
     */
    const PAY_SUBMIT_URL = 's1/openapi/openapi/base/arch/completepullarchinfo';
    /**
     *用户根据商品ID获取商品信息接口
     */
    const SINGLE_INFO_URL = 's1/openapi/openapi/base/arch/singlepullarchinfo';

    /**
     *用户根据商品ID获取商品库存信息接口
     */
    const SINGLE_INFO_STOCK_URL = 's1/openapi/openapi/base/arch/singlepullarchinfo';

    /**
     *用户全量获取店铺信息接口
     */
    const SHOP_ALL_INFO_URL = 's1/openapi/openapi/base/arch/completepullshopinfo';

    /**
     *用户根据店铺ID获取店铺信息接口
     */
    const SHOP_INFO_URL = 's1/openapi/openapi/base/arch/singlepullshopinfo';

    /**
     *用户根据菜谱/销售方案ID获取菜谱/销售方案详情
     */
    const SHOP_MENU_URL = 's1/openapi/openapi/base/arch/singlepullarchinfo';

    /**
     *下单创建订单
     */
    const CREATE_ORDER_URL = 's1/openapi/openapi/base/order/create';

    /**
     * 服务商ID
     * @var string
     */
    protected $ispInfoId;
    /**
     * 请求来源-集团ID
     */
    protected $centerId;
    /**
     * 接口根地址
     * @var string
     */
    protected $BaseUrl;
    /**
     * 公钥
     * @var string
     */
    protected $public_key;

    public function __construct()
    {
        parent::__construct();
        if ($this->isDevelopment()) {
            //预发布环境
            $this->ispInfoId     = '10004';
            $this->centerId     = '3261';
            $this->public_key   = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAZ3qXoX1uvrvUOXU1sI7kpZc85AfT0vtb2AzUp+LyZyOyC0U2FNDrdfGkzAUZidIqt0aVRHvEyFyV4ttsubiLG/fF40qDmtBgLySSGJcXwbjEM0f3ZDDLAbejsncuXOQKxytHUCxJ6XlffnEiBfbs+8BzDpWssdfpIVQ5wUWEnQIDAQAB';
            $this->BaseUrl      = 'http://221.239.30.130:8280/';
        }else{
            //正式环境
            $this->ispInfoId     = '10004';
            $this->centerId     = '3819';
            $this->public_key   = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAZ3qXoX1uvrvUOXU1sI7kpZc85AfT0vtb2AzUp+LyZyOyC0U2FNDrdfGkzAUZidIqt0aVRHvEyFyV4ttsubiLG/fF40qDmtBgLySSGJcXwbjEM0f3ZDDLAbejsncuXOQKxytHUCxJ6XlffnEiBfbs+8BzDpWssdfpIVQ5wUWEnQIDAQAB';
            $this->BaseUrl      = 'https://lp.tcsl.com.cn/';
        }
    }

    /**
     * 用户全量获取信息接口
     * @param $Crm_type
     * @return mixed
     * 1:商品 2:商品类别 3:单位 4:套餐 5:券 6:支付方式 7:营销活动 8:菜谱/销售方案
     */
    public function CompletePullArchInfo(int $Crm_type)
    {
        $data['centerId'] = $this->centerId;
        $data['type'] = $Crm_type;
        $data['limit'] = 5000;
        $data['page'] = 1;
        $data_arr['ispInfoId'] = $this->ispInfoId;
        $data_arr['data'] = self::encryptByPublicKey(json_encode($data), $this->public_key);
        $post_url = $this->BaseUrl . self::PAY_SUBMIT_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($data_arr));
        $return_data = json_decode($api_return_do_pay_data,true);
        $arr = self::decryptByPublicKey($return_data['data'], $this->public_key);
        $return_data_arr = json_decode($arr,true);
        return $return_data_arr;
    }

    /**
     * 用户全量获取余量接口（1.0 老库存）
     * @param int $page
     * @param int $limit
     * @return mixed
     */
    public function completePullArchInfoStock(int $page = 1, int $limit = 1000)
    {
        $params = ['centerId' => $this->centerId, 'type' => 9, 'limit' => $limit, 'page' => $page];
        $map = [
            'ispInfoId' => $this->ispInfoId,
            'data' => self::encryptByPublicKey(json_encode($params), $this->public_key)
        ];
        $post_url = $this->BaseUrl . self::PAY_SUBMIT_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($map));
        $return_data = json_decode($api_return_do_pay_data,true);
        $arr = self::decryptByPublicKey($return_data['data'], $this->public_key);
        return json_decode($arr,true);
    }

    /**
     * 根据店铺用户全量获取余量接口（1.0 老库存）
     * @param int $shopId
     * @param int $page
     * @param int $limit
     * @return mixed
     */
    public function completeShopPullArchInfoStock(int $shopId, int $page = 1, int $limit = 10000)
    {
        $params = ['shopId' => $shopId, 'type' => 9, 'limit' => $limit, 'page' => $page];
        $map = [
            'ispInfoId' => $this->ispInfoId,
            'data' => self::encryptByPublicKey(json_encode($params), $this->public_key)
        ];
        $post_url = $this->BaseUrl . self::PAY_SUBMIT_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($map));
        $return_data = json_decode($api_return_do_pay_data,true);
        $arr = self::decryptByPublicKey($return_data['data'], $this->public_key);
        return json_decode($arr,true);
    }

    /**
     * 用户根据商品ID获取商品信息接口
     * @param $goods_crm_code
     * @return mixed
     */
    public function SinglePullArchInfo($goods_crm_code)
    {
        $data['id']     =    $goods_crm_code;
        $data['centerId']     = $this->centerId;
        $data['type']     = 1;
        $data_arr['ispInfoId']=$this->ispInfoId;
        $data_arr['data']=self::encryptByPublicKey(json_encode($data),$this->public_key);
        $post_url        = $this->BaseUrl . self::SINGLE_INFO_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($data_arr));
        $return_data =json_decode($api_return_do_pay_data,true);
        $arr =self::decryptByPublicKey($return_data['data'],$this->public_key);
        $return_data_arr =json_decode($arr,true);
        return $return_data_arr;
    }

    /**
     * 用户根据商品ID获取商品库存
     * @param $goods_crm_code
     * @param $shop_id
     *
     * @return mixed
     */
    public function SinglePullArchInfoStock($goods_crm_code,$shop_id)
    {
        $goods_crm_code = trim($goods_crm_code);
        $lsy_shop_no=ShopModel::query()->where('shop_id',$shop_id)->value('lsy_shop_no');
        $data['id']     =$goods_crm_code;
        $data['shopId']     = $lsy_shop_no;
        $data['type']     = 6;
        $data_arr['ispInfoId']=$this->ispInfoId;
        $data_arr['data']=self::encryptByPublicKey(json_encode($data),$this->public_key);
        $post_url        = $this->BaseUrl . self::SINGLE_INFO_STOCK_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($data_arr));
        $return_data =json_decode($api_return_do_pay_data,true);
        $arr =self::decryptByPublicKey($return_data['data'],$this->public_key);
        $return_data_arr =json_decode($arr,true);
        return $return_data_arr;
    }
    /**
     * 用户全量获取店铺信息接口
     */
    public function CompletePullShopInfo()
    {
        $data['centerId']     = $this->centerId;
        $data['limit']     = 10;
        $data['page']     = 1;
        $data_arr['ispInfoId']=$this->ispInfoId;
        $data_arr['data']=self::encryptByPublicKey(json_encode($data,true),$this->public_key);
        $post_url        = $this->BaseUrl . self::SHOP_ALL_INFO_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($data_arr));
        $return_data =json_decode($api_return_do_pay_data,true);
        $arr =self::decryptByPublicKey($return_data['data'],$this->public_key);
        $return_data_arr =json_decode($arr,true);
        return $return_data_arr;
    }

    /**
     * 用户全量获取信息余量接口
     * @param $shopId
     * @param $Crm_type
     * @return mixed
     */
    public function CompletePullArchInfoQuantity($shopId,$Crm_type)
    {
        $data['centerId']     = $this->centerId;
        $data['shopId']     = $shopId;
        $data['type']     = $Crm_type;
        $data['limit']     = 600;
        $data['page']     = 1;
        $data_arr['ispInfoId']=$this->ispInfoId;
        $data_arr['data']=self::encryptByPublicKey(json_encode($data),$this->public_key);
        $post_url        = $this->BaseUrl . self::PAY_SUBMIT_URL;
        $api_return_do_pay_data = self::do_request_post($post_url, json_encode($data_arr));
        $return_data =json_decode($api_return_do_pay_data,true);
        $arr =self::decryptByPublicKey($return_data['data'],$this->public_key);
        $return_data_arr =json_decode($arr,true);
        return $return_data_arr;
    }

    /**
     * 用户根据店铺ID获取店铺信息接口
     * @param $shopId
     * @return mixed
     */
    public function  singlePullShopInfo($shopId){
        $data['centerId']     = $this->centerId;
        $data['shopId']     = $shopId;
        $data_arr['ispInfoId']=$this->ispInfoId;
        $data_arr['data']=self::encryptByPublicKey(json_encode($data,true),$this->public_key);
        $post_url        = $this->BaseUrl . self::SHOP_INFO_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($data_arr));
        $return_data =json_decode($api_return_do_pay_data,true);
        $arr =self::decryptByPublicKey($return_data['data'],$this->public_key);
        $return_data_arr =json_decode($arr,true);
        return $return_data_arr;
    }

    /**
     * 用户根据菜谱/销售方案ID获取菜谱/销售方案详情
     * @param string $menu_id
     * @param int $page
     * @param int $limit
     * @return mixed
     */
    public function  singlePullShopInfoMenu(string $menu_id, int $page = 1, int $limit = 5000){
        $params = ['centerId' => $this->centerId, 'id' => $menu_id, 'type' => 8, 'limit' => $limit, 'page' => $page];
        $map = [
            'ispInfoId' => $this->ispInfoId,
            'data' => self::encryptByPublicKey(json_encode($params), $this->public_key)
        ];
        $post_url = $this->BaseUrl . self::SHOP_MENU_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($map));
        $return_data = json_decode($api_return_do_pay_data,true);
        $arr = self::decryptByPublicKey($return_data['data'],$this->public_key);
        return json_decode($arr,true);
    }


    /**
     * 龙收银下单接口
     * @param $goods_crm_code
     * @return mixed
     */
    public function CrmCreateOrder($goods_crm_code)
    {
        $goods_arr =$this->SinglePullArchInfo($goods_crm_code);
        $data['ispInfoName']='一路小跑';
        $data['orderType']     = 1;
        $data['thirdTransactionId']     = 'T0200525095825005300000003';
        $data['createShopId']     = 4164;
        $data['origTotal']     = 0.01;
        $data['lastTotal']     = 0;
        $data['createTime']     = '2020-05-19 10:30:50';
        $data['settleState']     = 0;
        $data['itemInfoList']     = [
            'id'=>$goods_arr['id'],
            'name'=>$goods_arr['name'],
            'unitId'=>$goods_arr['unitId'],
            'itemClassId'=>$goods_arr['itemClassId'],
            'origPrice'=>$goods_arr['costPrice'],
            'lastPrice'=>$goods_arr['stdPrice'],
            'costPrice'=>$goods_arr['costPrice'],
            'qty'=>2,
            'itemType'=>0,
        ];
        $data['paywayInfoList']     = [
            'paywayId'=>1,
            'payMoney'=>$goods_arr['stdPrice'],
        ];
        $data_arr['ispInfoId']=$this->ispInfoId;
        $data_arr['data']=self::encryptByPublicKey(json_encode($data,true),$this->public_key);
        $post_url        = $this->BaseUrl . self::CREATE_ORDER_URL;
        $api_return_do_pay_data = $this->do_request_post($post_url, json_encode($data_arr));
        $return_data =json_decode($api_return_do_pay_data,true);
        $arr =self::decryptByPublicKey($return_data['data'],$this->public_key);
        $return_data_arr =json_decode($arr,true);
        return $return_data_arr;
    }
    /**
     * RSA解密
     * @param $data
     * @param $public_key
     * @return bool|string
     */
    private static  function encryptByPublicKey($data, $public_key)
    {
        // 每64位进行换行
        $key = (wordwrap($public_key, 64, "\n", true))."\n";
        $pem_key = "-----BEGIN PUBLIC KEY-----\n" . $key . "-----END PUBLIC KEY-----\n";
        $encrypt='';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, $pem_key,OPENSSL_PKCS1_PADDING);
            $encrypt .= $encryptData;
        }
        return base64_encode($encrypt);
    }
    /**
     * RSA解密
     * @param $data
     * @param $public_key
     * @return string
     */
    private static function decryptByPublicKey($data,$public_key)
    {
        // 每64位进行换行
        $key = (wordwrap($public_key, 64, "\n", true))."\n";
        $pem_key = "-----BEGIN PUBLIC KEY-----\n" . $key . "-----END PUBLIC KEY-----\n";
        $decrypt = '';
        foreach (str_split(base64_decode($data), 128) as $chunk) {
            openssl_public_decrypt($chunk, $decryptData,$pem_key);
            $decrypt .= $decryptData;
        }
        return $decrypt;
    }

}
